class Grade < SourceAdapter
  def initialize(source) 
    @base = 'http://10.10.10.154:3000/grades'
    super(source)
  end
 
  def login
    # TODO: Login to your data source here if necessary
  end
 
  def query(params=nil)
    # TODO: Query your backend data source and assign the records 
    # to a nested hash structure called @result. For example:
    # @result = { 
    #   "1"=>{"name"=>"Acme", "industry"=>"Electronics"},
    #   "2"=>{"name"=>"Best", "industry"=>"Software"}
    # }
    parsed = JSON.parse(RestClient.get("#{@base}.json").body)
    
        @result={}
        parsed.each do |item|
          @result[item["grade"]["id"].to_s] = item["grade"]
        end if parsed
  end
 
  def sync
    # Manipulate @result before it is saved, or save it 
    # yourself using the Rhoconnect::Store interface.
    # By default, super is called below which simply saves @result
    super
  end
 
  def create(create_hash)
    # TODO: Create a new record in your backend data source
    client_id = Store.get_value('client_id')
    res = RestClient.post("#{@base}.json",{:grade => create_hash, :client_id => client_id})
    
        # After create we are redirected to the new record. 
        # We need to get the id of that record and return 
        # it as part of create so rhosync can establish a link 
        # from its temporary object on the client to this newly 
        # created object on the server
        JSON.parse(
          RestClient.get("#{res.headers[:location]}.json").body
        )["grade"]["id"]
  end
 
  def update(update_hash)
    # TODO: Update an existing record in your backend data source
    obj_id = update_hash['id']
        update_hash.delete('id')   
        RestClient.put("#{@base}/#{obj_id}",:grade => update_hash)
  end
 
  def delete(delete_hash)
    # TODO: write some code here if applicable
    # be sure to have a hash key and value for "object"
    # for now, we'll say that its OK to not have a delete operation
    # raise "Please provide some code to delete a single object in the backend application using the object_id"
    RestClient.delete("#{@base}/#{delete_hash['id']}")
  end
 
  def logoff
    # TODO: Logout from the data source if necessary
  end
end